package org.crazyit.cloud;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import lombok.Data;

import java.util.List;
import java.util.Random;

@Data
public class MyRule implements IRule {

    private ILoadBalancer lb;

    public MyRule(ILoadBalancer lb) {
        this.lb = lb;
    }

    public MyRule() {
        super();
    }

    public Server choose(Object o) {
        Random random = new Random();
        int rNum = random.nextInt(10);
        List<Server> servers = lb.getAllServers();

        if(rNum > 7){
            return getServerByPort(servers,8081);
        }
        return getServerByPort(servers,8080);

    }

    /**
     * 写一个工具方法来根据端口获取服务
     */
    private Server getServerByPort(List<Server> servers ,int port){
        for (Server server : servers) {
            if(server.getPort() == port){
                return server;
            }
        }
        return null;
    }


    public void setLoadBalancer(ILoadBalancer iLoadBalancer) {
        this.lb = lb;
    }

    public ILoadBalancer getLoadBalancer() {
        return this.lb;
    }

}
